package com.socket.secure.util;

import cn.hutool.crypto.CryptoException;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.crypto.asymmetric.KeyType;
import cn.hutool.crypto.asymmetric.RSA;
import com.socket.secure.constant.RequsetTemplate;
import com.socket.secure.exception.InvalidRequestException;

import java.security.KeyPair;

/**
 * RSA encryption tool
 */
public class RSAUtil {
    /**
     * Generate RSA KeyPair
     *
     * @return KeyPair
     */
    public static KeyPair generateKeyPair() {
        return SecureUtil.generateKeyPair("RSA", 1024);
    }

    /**
     * RSA encrypt
     *
     * @param plaintext plaintext
     * @param pubkey    public key
     * @return ciphertext
     */
    public static String encrypt(String plaintext, String pubkey) {
        try {
            return new RSA(null, pubkey).encryptHex(plaintext.getBytes(), KeyType.PublicKey);
        } catch (CryptoException e) {
            throw new InvalidRequestException(RequsetTemplate.RSA_ENCRYPT_ERROR, plaintext);
        }
    }

    /**
     * RSA decrypt
     *
     * @param ciphertext ciphertext
     * @param prikey     private key
     * @return plaintext
     */
    public static String decrypt(String ciphertext, String prikey) {
        try {
            return new RSA(prikey, null).decryptStr(ciphertext, KeyType.PrivateKey);
        } catch (CryptoException e) {
            throw new InvalidRequestException(RequsetTemplate.RSA_DECRYPT_ERROR, ciphertext);
        }
    }
}
